package com.lin.missyou.service;

import com.lin.missyou.bo.OrderMessageBO;
import com.lin.missyou.core.enumeration.OrderStatus;
import com.lin.missyou.exception.http.ServerErrorException;
import com.lin.missyou.model.Order;
import com.lin.missyou.model.UserCoupon;
import com.lin.missyou.repository.OrderRepository;
import com.lin.missyou.repository.UserCouponRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class CouponBackService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private UserCouponRepository UserCouponRepository;

    /**
     * 先判断订单状态，在归还优惠卷
     *
     * @param orderMessageBO
     */
//    @EventListener
    @Transactional
    public void returnBack(OrderMessageBO orderMessageBO) {
        Long orderId = orderMessageBO.getOrderId();
        Long userId = orderMessageBO.getUserId();
        Long couponId = orderMessageBO.getCouponId();
        if (couponId == -1) {
            return;
        }
        Order order = orderRepository.findById(orderId)
                .orElseThrow(() -> new ServerErrorException(9999));

        if (order.getStatusEnum().equals(OrderStatus.UNPAID)
                || order.getStatusEnum().equals(OrderStatus.CANCELED)) {
            UserCouponRepository.returnBack(userId, couponId);
        }
    }
}
